package com.android.manghe.mine.activity

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Html
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.MVPActivity
import com.android.base.okhttp.okUtil.OKHttpUtil
import com.android.base.tools.StatusBarUtil
import com.android.base.tools.ToastUtil
import com.android.base.tools.permission.OnPermissionResultListener
import com.android.base.tools.permission.PermissionUtil
import com.android.manghe.R
import com.android.manghe.cache.UserHolder
import com.android.manghe.common.model.BaseBack
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.mine.model.InvitationDataRes
import com.android.manghe.mine.presenter.PShare
import com.githang.statusbar.StatusBarCompat
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_share.*
import okhttp3.Call
import java.util.*


class ShareActivity : MVPActivity<PShare>(), View.OnClickListener {

    private var shareTitle = ""
    private var shareContent = ""
    private var sharePic = ""
    private var shareUrl = ""
    private var mShareAPI: UMShareAPI? = null
    private var myInviteCode = ""


    override fun getLayoutId(): Int {
        return R.layout.activity_share
    }

    override fun showToolBarType(): ETitleType {
        return ETitleType.NO_TITLE
    }

    override fun initData(savedInstanceState: Bundle?) {
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.transparent))

        val lp = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        lp.topMargin = StatusBarUtil.getStatusBarHeight(mContext) + 12
        layoutTop.layoutParams = lp

        ivBack.setOnClickListener { finish() }
        ivWechat.setOnClickListener(this)
        ivCircle.setOnClickListener(this)
        ivQQ.setOnClickListener(this)
        ivQZone.setOnClickListener(this)
        tvMyInviteCode.setOnClickListener {
            //获取剪贴板管理器：
            val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val mClipData = ClipData.newPlainText("Label", myInviteCode)
            cm.primaryClip = mClipData

            ToastUtil.showShort(this@ShareActivity, "复制成功")
        }
        tvConfirm.setOnClickListener {
            if(etInviteCode.text.toString().trim().isEmpty()){
                ToastUtil.showShort(this@ShareActivity, "请填写您师傅的邀请码")
                return@setOnClickListener
            }
            sendInviteCode(etInviteCode.text.toString().trim())
        }
        mShareAPI = UMShareAPI.get(this)
        getTip()
    }

    private val shareListener = object : UMShareListener {
        /**
         * @descrption 分享成功的回调
         */
        override fun onResult(p0: SHARE_MEDIA?) {
            ToastUtil.showShort(this@ShareActivity, "分享成功")
        }

        /**
         * @descrption 分享取消的回调
         */
        override fun onCancel(p0: SHARE_MEDIA?) {
            ToastUtil.showShort(this@ShareActivity, "取消分享")
        }

        /**
         * @descrption 分享失败的回调
         */
        override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
            ToastUtil.showShort(this@ShareActivity, "分享失败")
        }

        /**
         * @descrption 分享开始的回调
         */
        override fun onStart(p0: SHARE_MEDIA?) {
        }

    }


    override fun onClick(v: View?) {
        PermissionUtil.requestPermissions(
            this, object : OnPermissionResultListener {
                override fun onGranted(permissions: MutableList<String>?) {
                    val web = UMWeb(shareUrl)
                    web.title = shareTitle//标题
                    web.setThumb(UMImage(this@ShareActivity, sharePic))  //缩略图
                    web.description = shareContent//描述
                    when (v) {
                        ivWechat -> {
                            if (mShareAPI!!.isInstall(this@ShareActivity, SHARE_MEDIA.WEIXIN)) {
                                ShareAction(this@ShareActivity)
                                    .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                                    .withMedia(web)
                                    .setCallback(shareListener)//回调监听器
                                    .share()
                            } else {
                                ToastUtil.showShort(this@ShareActivity, "请安装微信客户端")
                            }
                        }
                        ivCircle -> {
                            if (mShareAPI!!.isInstall(this@ShareActivity, SHARE_MEDIA.WEIXIN)) {
                                web.title = shareContent //标题
                                ShareAction(this@ShareActivity)
                                    .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                                    .withMedia(web)
                                    .setCallback(shareListener)//回调监听器
                                    .share()
                            } else {
                                ToastUtil.showShort(this@ShareActivity, "请安装微信客户端")
                            }
                        }
                        ivQQ -> {
                            if (mShareAPI!!.isInstall(this@ShareActivity, SHARE_MEDIA.QQ)) {
                                ShareAction(this@ShareActivity)
                                    .setPlatform(SHARE_MEDIA.QQ)//传入平台
                                    .withMedia(web)
                                    .setCallback(shareListener)//回调监听器
                                    .share()
                            } else {
                                ToastUtil.showShort(this@ShareActivity, "请安装QQ客户端")
                            }
                        }
                        ivQZone -> {
                            if (mShareAPI!!.isInstall(this@ShareActivity, SHARE_MEDIA.QQ)) {
                                ShareAction(this@ShareActivity)
                                    .setPlatform(SHARE_MEDIA.QZONE)//传入平台
                                    .withMedia(web)
                                    .setCallback(shareListener)//回调监听器
                                    .share()
                            } else {
                                ToastUtil.showShort(this@ShareActivity, "请安装QQ客户端")
                            }
                        }
                    }
                }
            },
            Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE,
            Permission.READ_PHONE_STATE
        )

    }

    fun sendCodeOk(){
        etInviteCode.text.clear()
    }

    private fun sendInviteCode(code: String){
        showLoadingDialog()
        p.sendCode(code)
    }

    private fun getTip() {
        showLoadingDialog()
        val headMap = HashMap<String, String>()
        headMap["UID"] = UserHolder.getUID(this)
        headMap["TOKEN"] = UserHolder.getUserInfo(this)!!.TOKEN
        val dataMap = HashMap<String, String>()
        dataMap["app_name"] = "meng_xiang"
        OKHttpUtil(this).urlByHeadData(
            ConstantsUrl.domain + ConstantsUrl.MEMBER_INVITATION,
            dataMap,
            headMap
        )
            .get()
            .execute(object : BaseBack<InvitationDataRes>() {
                override fun onSuccess(call: Call, res: InvitationDataRes) {
                    hideLoadingDialog()
                    if (res != null && res.code == 0 && res.data != null) {
                        tvMyInviteCode.text = "我的邀请码：${res.data.mid}(点击复制)"
                        myInviteCode = res.data.mid
                        tvContent.text = Html.fromHtml(res.data.explain)
                        if (res.data.comment != null) {
                            shareTitle = res.data.comment.site_name
                            shareContent = res.data.comment.site_name + "-" + res.data.comment.text
                            shareUrl = res.data.comment.url
                            sharePic = res.data.comment.pic
                        }
                        try {
                            if (!TextUtils.isEmpty(res.data.invite_info.nickname)) {
                                etInviteCode.setText(res.data.invite_info.nickname)
                                etInviteCode.isEnabled = false
                                tvConfirm.text = "已拜师"
                                tvConfirm.isEnabled = false
                            }
                        } catch (e: java.lang.Exception) {
                            e.printStackTrace()
                        }
                    }
                }

                override fun onFailure(e: Exception) {
                    super.onFailure(e)
                    hideLoadingDialog()
                }

                override fun onComplete() {

                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        UMShareAPI.get(this).release()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }
}